<script
	lang="ts"
	setup
>
import { systemMessagePut } from '@/api'
import EmptyModal from '@/components/EmptyModal.vue'
import type { ISystemMessagePut } from '@/typed/request'
import type { OSystemMessageListGetItem } from '@/typed/response'
import { type FormInst, type FormRules, type SelectOption } from 'naive-ui'
import { ref, watch } from 'vue'

interface IProps {
	show: boolean;
	data?: OSystemMessageListGetItem;
	width?: number | string;
}

const formRef = ref<FormInst | null>(null)
const emit = defineEmits(['update:show', 'update:list', 'cancel'])
const props = withDefaults(defineProps<IProps>(), {
	width: 500
})
const initForm: ISystemMessagePut = {
	id: 0,
	title: '',
	content: '',
	toUserNos: []
};

const loading = ref(false)
const modalForm = ref<ISystemMessagePut>({ ...initForm })
const userList = ref<SelectOption[]>([])
const rules: FormRules = {
	title: [{
		required: true,
		message: '请输入标题',
		trigger: ['blur', 'input']
	}],
	content: [{
		required: true,
		message: '请输入消息内容',
		trigger: ['blur', 'input']
	}],
}

watch(() => props.data, () => {
	if (props.data) {
		modalForm.value = {
			id: props.data.id,
			title: props.data.title,
			content: props.data.content,
			toUserNos: props.data.toUserNos
		}
		userList.value = modalForm.value.toUserNos?.map(i => {
			return {
				label: i,
				value: i,
				disabled: true
			}
		}) || []
	} else {
		modalForm.value = initForm;
	}

})

async function onConfirm() {
	formRef.value?.validate(async (errors) => {
		if (!errors) {
			loading.value = true
			const { code } = await systemMessagePut({
				...modalForm.value
			})
			loading.value = false
			if (code === 200) {
				window.$message.success('保存成功')
				modalForm.value = { ...initForm }

				emit('update:list')
			}
		}
	})
}

function onUpdateShow(show: boolean) {
	emit('update:show', show)
}
</script>

<template>
	<EmptyModal
		:show="show"
		@update:show="onUpdateShow"
		:loading="loading"
		:width="600"
		title="编辑消息"
		@confirm="onConfirm"
		@close="emit('cancel')"
		@cancel="emit('cancel')"
	>
		<n-form
			ref="formRef"
			:model="modalForm"
			label-placement="left"
			label-width="110"
			:rules="rules"
		>
			<n-form-item
				label="消息标题"
				path="title"
			>
				<n-input
					placeholder="请输入标题"
					v-model:value="modalForm.title"
				/>
			</n-form-item>
			<n-form-item
				label="消息内容"
				path="content"
			>
				<n-input
					type="textarea"
					placeholder="请输入消息内容"
					v-model:value="modalForm.content"
				/>
			</n-form-item>
			<n-form-item
				label="接收用户"
				path="toUserNos"
			>
				<n-select
					placeholder="请选择用户"
					multiple
					:options="userList"
					v-model:value="modalForm.toUserNos"
				/>
			</n-form-item>
		</n-form>
	</EmptyModal>
</template>

<style
	lang="less"
	scoped
>

</style>
